﻿using S7.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using xktComm;

namespace DataCollection
{
    public class CollectionDriver
    {
        private Plc plc = null;
        private bool ConnectionState = false;
        private CancellationTokenSource cts = null;
        string PlcIp = XmlHelper.ReadXmlFirst("PLC");
        public  void StartCollectionData()
        {                    
            if (!ConnectionState)
            {
                try
                {
                    this.plc = new Plc(CpuType.S7300, PlcIp, 0, 2);
                    plc.Open();
                }
                catch
                {
                    return;
                }
                this.ConnectionState = true;
                //开启线程
                cts = new CancellationTokenSource();
                Task.Run(new Action(() =>
                {
                    ReadData();
                }), cts.Token);

            }
            else
            {

            }
        }

       

        private void ReadData()
        {
            //数据读取
            while (!cts.IsCancellationRequested)
            {
                try
                {
                    bool startBit = true;// (bool)plc.Read("DB400.DBX0.0");
                    if (startBit)
                    {
                        string strTime = DateTime.Now.ToString(("yyyy-MM-dd HH:mm:ss"));
                        // plc.Write("DB400.DBX0.0", false);
                        byte[] result = plc.ReadBytes(S7.Net.DataType.DataBlock, 400, 0, 66);

                        //string strTime = StringLib.GetSiemensStringFromByteArray(result, 2, 20);
                        string reportName = StringLib.GetSiemensStringFromByteArray(result, 24, 20);

                        short reportType = ShortLib.GetShortFromByteArray(result, 46);
                        short stepNo = ShortLib.GetShortFromByteArray(result, 48);
                        float tt1 = FloatLib.GetFloatFromByteArray(result, 50);
                        float tt2 = FloatLib.GetFloatFromByteArray(result, 54);
                        string sql = "insert into tblData(strTime,reportName,reportType,tt1,tt2,stepNo) VALUES ('" + strTime + "','" + reportName + "'," + reportType.ToString() + "," + tt1.ToString() + "," + tt2.ToString() + "," + stepNo.ToString() + ")";
                        LogInfo.WriteLogs(sql);
                        SQLHelper.ExecuteNonQuery(sql);
                    }
                }t
                catch
                {
                }
                Thread.Sleep(1000);
            }
        }
    }
}
